/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="data-list__container">
        <div class="table-data">
            <sf-grid>
                <sf-toolbar ref="toolbar">
                    <sf-button
                        class="btn-blank"
                        icon-cls="iconsip-refresh"
                        @click="_onRefresh">
                        <lang>刷新</lang>
                    </sf-button>
                    <sf-button
                        ref="submit"
                        class="creat-button btn-blank"
                        icon-cls="iconxinzeng2"
                        @click="_addDataSourceConnect">
                        <lang>新建连接</lang>
                    </sf-button>
                    <sf-searchfield
                        v-model="searchParams.keyword"
                        class="pull-right"
                        placeholder="请输入关键字"
                        @trigger="_startSearch"
                        @clear="_startSearch" />
                </sf-toolbar>
                <sf-table
                    ref="table"
                    :options="options_fix"
                    @pagechange="_onPageChange"
                    @sizechange="_onSizeChange">
                    <sf-table-column :default-width="30"

                                     type="index">
                        <lang>序号</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="name"
                        :default-width="100">
                        <lang>数据源名称</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="type"
                        :default-width="150">
                        <lang>数据库类型</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="url"
                        :default-width="100">
                        <lang>服务器地址</lang>
                    </sf-table-column>
                    <sf-table-column data-index="opr"
                                     :default-width="100">
                        <lang>操作</lang>
                    </sf-table-column>
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a
                                class="link-btn"
                                @click="_deleteSource(record)">
                                <lang>删除</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </sf-grid>
        </div>
    </div>
</template>

<script lang="ts">


import { encodeDate } from 'src/util/format';
const PAGE_COUNT = 20;
import { Component, Vue } from 'vue-property-decorator';

import store from 'src/vuex/store';
let userID = store.state.userId;

import urlAdapter from 'src/home/mod_common/url_adapter';
const DATASOURCE_URLS = {
    get: urlAdapter(`user/${userID}/dataSource/database`),
    delete: urlAdapter('dataSource'),
    post:urlAdapter(`user/${userID}/dataSource`)
};
import selectDataSource from '../label_form/select_datasource.vue';
import addEsSourceForm from '../label_form/add_es_source.vue';
import addMgdbSourceForm from '../label_form/add_mgdb_source.vue';

interface DataSourceParams{
    createTime: string;
    dataBaseName: string;
    dataBasePassword: string;
    dataBaseUserName: string;
    description: string;
    fileName: string;
    filepath: string;
    id: null;
    name: string;
    type: string;
    updateTime: string;
    url: string;
}


@Component
export default class DataListContainer extends Vue {

    options_fix= {
        bufferView: false,
        selectionHide: true,

        // 配置这个后才可以实现保持勾选状态
        idProperty: 'id',
        pagination: {
            activePage: 1,
            pageSize: PAGE_COUNT,
            pageSizes: [Number('10'), Number('20'), Number('50')]
        }
    }
    searchParams =  {
        pageSize: PAGE_COUNT,
        pageNum: 0,
        DataSourceId: '',
        keyword:''
    }
    async mounted () {
        await this.refreshGrid();
    }

    // 刷新grid
    async refreshGrid () {
        this.$mask();

        let jsonData = await this.$ajax.get(DATASOURCE_URLS.get, this.searchParams);
        this.$unmask();
        let table = this.$refs.table;
        let {success, msg, data} = jsonData;
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            // @ts-ignore
            table.loadData([]);
            return;
        }
        if (!table) {
            return;
        }
        // @ts-ignore
        table.getPagination().setTotal(data.total);
        // @ts-ignore
        table.loadData(data.list || []);
    }

    // 新增es
    async ajaxSubmitDataSourceInfo (params: DataSourceParams, formWin: vue, fetch = 'post') {
        formWin.$mask();
        let ADD_TYPE_URL = `${DATASOURCE_URLS.post}`;
        let jsonData = await this.$ajax[fetch](ADD_TYPE_URL, params);
        formWin.$unmask();
        let {success, msg} = jsonData;
        if (!success) {
            return this.$showErr(msg || _('保存失败'));
        }
        this.$ok(_('保存成功'));
        formWin.hide();

        this.selectDataSourceWin.hide();

        await this.refreshGrid();
    }

    // 删除数据源

    _deleteSource (record: DataSourceParams) {
        let item = record;
        let params = {};
        let title = '';
        if (item) {
            // @ts-ignore
            params.dataSourceId = item.id;
            title = item.name;
        }
        // @ts-ignore
        this.$confirm({
            title: _('提示'),
            subTitle: _('确定要删除{0}数据源吗？', title),
            msg:'',
            icon: 'warning',
            autoClose: true,
            callback: actionName => {
                if (actionName === 'submit') {
                    // @ts-ignore
                    this.ajaxDeleteSource(params);
                }
            }
        });
    }

    // 执行删除操作
    async ajaxDeleteSource (params: DataSourceParams) {
        this.$mask();
        // @ts-ignore
        let jsonData = await this.$ajax.delete(`${DATASOURCE_URLS.delete}/${params.dataSourceId}`, params);
        this.$unmask();
        let {success, msg} = jsonData;
        if (!success) {
            return this.$showErr(msg || _('删除失败'));
        }
        this.$ok(_('删除成功'));

        this.refreshGrid();
    }

    // 新增数据源弹窗
    _createSelectDataSourceWin () {
        if (!this.selectDataSourceWin) {
            this.selectDataSourceWin = this.$modal(selectDataSource, {
                autoDestory: true
            });
        }
        return this.selectDataSourceWin;
    }

    // 新增数据源
    _addDataSourceConnect () {
        this._addEsDataSourceConnect();
    }

    // 创建ES数据源弹窗
    _createEsDataSourceWin () {
        if (!this.esDataSourceFormWin) {
            this.esDataSourceFormWin = this.$modal(addEsSourceForm, {
                autoDestory: true
            });
        }
        return this.esDataSourceFormWin;
    }

    _addEsDataSourceConnect () {
        let formWin = this._createEsDataSourceWin();
        formWin.open({
            reset: true,
            title: _('新建连接'),
            buttons:[
                { actionName: 'back', text: _('上一步') },
                { actionName: 'submit', text: _('确定') },
                'cancel'
            ],
            callback:(actionName)=>{
                if (actionName === 'submit') {
                    if (!formWin.$refs.form.isValid()) {
                        this.$showErr(formWin.$refs.form.getInvalidMsgs());
                        return false;
                    }
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    if (!ajaxParams.statusSuccess) {
                        this.$showErr(_('连通性未成功，请验证服务器地址'));
                        return false;
                    }
                    this.ajaxSubmitDataSourceInfo(ajaxParams, formWin);
                } else if (actionName === 'back') {
                    formWin.hide();
                }
            }
        });
    }

    // 创建mgdb数据源弹窗
    _createMgDbDataSourceWin () {
        if (!this.mgDbDataSourceFormWin) {
            this.mgDbDataSourceFormWin = this.$modal(addMgdbSourceForm, {
                autoDestory: true
            });
        }
        return this.mgDbDataSourceFormWin;
    }

    _addMgDbDataSource () {
        let formWin = this._createMgDbDataSourceWin();
        formWin.open({
            reset: true,
            title: _('新建连接'),
            data:{
                dataType:'mongdb'
            },
            buttons:[
                { actionName: 'back', text: _('上一步') },
                { actionName: 'submit', text: _('确定') },
                'cancel'
            ],
            callback:(actionName: string)=>{
                if (actionName === 'submit') {
                    if (!formWin.$refs.form.isValid()) {
                        this.$showErr(formWin.$refs.form.getInvalidMsgs());
                        return false;
                    }
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    if (!ajaxParams.statusSuccess) {
                        this.$showErr(_('请先进行连通性测试'));
                        return false;
                    }
                    this.ajaxSubmitDataSourceInfo(ajaxParams, formWin);
                } else if (actionName === 'back') {
                    formWin.hide();
                }
            }
        });
    }

    // 创建mgdb数据源弹窗
    _createGraphDataSourceWin () {
        if (!this.graphDataSourceFormWin) {
            this.graphDataSourceFormWin = this.$modal(addMgdbSourceForm, {
                autoDestory: true
            });
        }
        return this.graphDataSourceFormWin;
    }

    _addGraphDataSource () {
        let formWin = this._createGraphDataSourceWin();
        formWin.open({
            reset: true,
            title: _('新建连接'),
            data:{
                dataType:'Nebula Graph'
            },
            buttons:[
                { actionName: 'back', text: _('上一步') },
                { actionName: 'submit', text: _('确定') },
                'cancel'
            ],
            callback:(actionName: string)=>{
                if (actionName === 'submit') {
                    if (!formWin.$refs.form.isValid()) {
                        this.$showErr(formWin.$refs.form.getInvalidMsgs());
                        return false;
                    }
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    if (!ajaxParams.statusSuccess) {
                        this.$showErr(_('请先进行连通性测试'));
                        return false;
                    }
                    this.ajaxSubmitDataSourceInfo(ajaxParams, formWin);
                } else if (actionName === 'back') {
                    formWin.hide();
                }
            }
        });
    }

    _onRefresh () {
        this.refreshGrid();
    }

    _startSearch () {
        this.refreshGrid();
    }
    _onPageChange (pageNum: number) {
        Object.assign(this.searchParams, {
            pageNum: pageNum - 1
        });
        this.refreshGrid();
    }
    _onSizeChange (nowPageIndex: number, nowPageSize: number) {
        Object.assign(this.searchParams, {
            pageNum: nowPageIndex - 1,
            pageSize: nowPageSize
        });
        this.refreshGrid();
    }

    encodeTime (time: string) {
        return encodeDate(time);
    }
};
</script>

<style lang="less">
    .data-list__container {
        height: calc(100% - 10px);
        margin-top: -7px;
        .table-data{
            border-top: 1px solid #ddd;
            height: 100%;
            .sfv-grid{
                border: none;
                height: 100%;
                display: flex;
                flex-direction: column;
                .sfv-table{
                    flex: 1;
                }
                .sfv-table_cell{
                    height: 35px !important;
                }
            }
        }
    }
</style>
